﻿module Loader

open System.Windows.Media.Imaging
open DocumentHost
open Http
open Uris
open HttpInterfaces

(* Fetches resources and (TODO:) chache *)
type Loader() =
    interface IResourceLoader with
        member this.fetchImage(uri:HttpUrl, callback) =
            let fetch1 =
                async {
                    let request = GetRequest(uri)
                    let! res = navigator request
                    match res with
                    | Failure(msg) -> ()
                    | Success(response, actualUri) ->
                        match response.body with
                        | BinaryBody(mime, stream) ->
                            let decoder : BitmapDecoder = 
                                match mime with
                                | "image/png" -> 
                                    PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None) :> BitmapDecoder
                                | "image/jpeg" -> 
                                    JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None) :> BitmapDecoder
                                | "image/gif" -> 
                                    GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None) :> BitmapDecoder
                                | _ -> null
                            if decoder <> null
                            then
                                let bitmapSource = decoder.Frames.[0]
                                do callback bitmapSource
                                return ()
                        | _ -> return ()
                    }
            Async.Start fetch1

